// Copyright 2024 The NativeLink Authors. All rights reserved.
//
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    See LICENSE file for details
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file is @generated by prost-build.
/// / Request object for keep alive requests.
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct KeepAliveRequest {}
/// / Request object for going away requests.
#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct GoingAwayRequest {}
/// / Represents the initial request sent to the scheduler informing the
/// / scheduler about this worker's capabilities and metadata.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ConnectWorkerRequest {
    /// / The list of properties this worker can support. The exact
    /// / implementation is driven by the configuration matrix between the
    /// / worker and scheduler.
    /// /
    /// / The scheduler may reject this worker if any property keys that
    /// / the scheduler is not configured to support, or may simply ignore
    /// / the unsupported properties.
    /// /
    /// / The details on how to use this property can be found here:
    /// / <https://github.com/TraceMachina/nativelink/blob/3147265047544572e3483c985e4aab0f9fdded38/nativelink-config/src/cas_server.rs>
    #[prost(message, repeated, tag = "1")]
    pub properties: ::prost::alloc::vec::Vec<
        super::super::super::super::super::build::bazel::remote::execution::v2::platform::Property,
    >,
    /// / Prefix to use for worker IDs. This is primarily used for debugging
    /// / or for other systems to identify workers. The scheduler will always
    /// / append this prefix to the assigned worker_id followed by a UUIDv6.
    #[prost(string, tag = "2")]
    pub worker_id_prefix: ::prost::alloc::string::String,
}
/// / The result of an ExecutionRequest.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ExecuteResult {
    /// / The `instance_name` this task was initially assigned to. This is set by the client
    /// / that initially sent the job as part of the BRE protocol.
    #[prost(string, tag = "1")]
    pub instance_name: ::prost::alloc::string::String,
    /// / The operation ID that was executed.
    #[prost(string, tag = "2")]
    pub operation_id: ::prost::alloc::string::String,
    /// / The actual response data.
    #[prost(oneof = "execute_result::Result", tags = "3, 4")]
    pub result: ::core::option::Option<execute_result::Result>,
}
/// Nested message and enum types in `ExecuteResult`.
pub mod execute_result {
    /// / The actual response data.
    #[derive(Clone, PartialEq, ::prost::Oneof)]
    pub enum Result {
        /// / Result of the execution. See `build.bazel.remote.execution.v2.ExecuteResponse`
        /// / for details.
        #[prost(message, tag = "3")]
        ExecuteResponse(
            super::super::super::super::super::super::build::bazel::remote::execution::v2::ExecuteResponse,
        ),
        /// / An internal error. This is only present when an internal error happened that
        /// / was not recoverable. If the execution job failed but at no fault of the worker
        /// / it should not use this field and should send the error via execute_response.
        #[prost(message, tag = "4")]
        InternalError(super::super::super::super::super::super::google::rpc::Status),
    }
}
/// / The result of an ExecutionComplete.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ExecuteComplete {
    /// / The operation ID that was executed.
    #[prost(string, tag = "1")]
    pub operation_id: ::prost::alloc::string::String,
}
/// / Result sent back from the server when a node connects.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ConnectionResult {
    /// / The worker ID to place in the action results generated by this worker.
    #[prost(string, tag = "1")]
    pub worker_id: ::prost::alloc::string::String,
}
/// / Request to kill a running operation sent from the scheduler to a worker.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct KillOperationRequest {
    /// / The the operation id for the operation to be killed.
    #[prost(string, tag = "1")]
    pub operation_id: ::prost::alloc::string::String,
}
/// / Communication from the scheduler to the worker.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UpdateForWorker {
    #[prost(oneof = "update_for_worker::Update", tags = "1, 2, 3, 4, 5")]
    pub update: ::core::option::Option<update_for_worker::Update>,
}
/// Nested message and enum types in `UpdateForWorker`.
pub mod update_for_worker {
    #[derive(Clone, PartialEq, ::prost::Oneof)]
    pub enum Update {
        /// / This will be sent only as the first item in the stream after the node
        /// / has connected.
        #[prost(message, tag = "1")]
        ConnectionResult(super::ConnectionResult),
        /// / Message used to let the worker know that it is still alive as well
        /// / as check to see if the worker is still alive. The worker
        /// / may close the connection if the scheduler has not sent any messages
        /// / after some amount of time (configured in the scheduler's
        /// / configuration).
        #[prost(message, tag = "2")]
        KeepAlive(()),
        /// / Informs the worker about some work it should begin performing the
        /// / requested action.
        #[prost(message, tag = "3")]
        StartAction(super::StartExecute),
        /// / Informs the worker that it has been disconnected from the pool.
        /// / The worker may discard any outstanding work that is being executed.
        #[prost(message, tag = "4")]
        Disconnect(()),
        /// / Instructs the worker to kill a specific running operation.
        #[prost(message, tag = "5")]
        KillOperationRequest(super::KillOperationRequest),
    }
}
/// / Communication from the worker to the scheduler.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UpdateForScheduler {
    #[prost(oneof = "update_for_scheduler::Update", tags = "1, 2, 3, 4, 5")]
    pub update: ::core::option::Option<update_for_scheduler::Update>,
}
/// Nested message and enum types in `UpdateForScheduler`.
pub mod update_for_scheduler {
    #[derive(Clone, PartialEq, ::prost::Oneof)]
    pub enum Update {
        /// / The initial request sent to the scheduler informing it of the
        /// / supported properties of this worker.
        #[prost(message, tag = "1")]
        ConnectWorkerRequest(super::ConnectWorkerRequest),
        /// / Message used to let the scheduler know that it is still alive as
        /// / well as check to see if the scheduler is still alive. The scheduler
        /// / may close the connection if the worker has not sent any messages
        /// / after some amount of time (configured in the scheduler's
        /// / configuration).
        #[prost(message, tag = "2")]
        KeepAliveRequest(super::KeepAliveRequest),
        /// / Informs the scheduler that the service is going offline and
        /// / should stop issuing any new actions on this worker.
        /// /
        /// / The worker may stay connected even after sending this command
        /// / and may even send an `ExecuteResult` after sending this command.
        /// / It is up to the scheduler implementation to decide how to handle
        /// / this case.
        /// /
        /// / Any job that was running on this instance likely needs to be
        /// / executed again, but up to the scheduler on how or when to handle
        /// / this case.
        #[prost(message, tag = "3")]
        GoingAwayRequest(super::GoingAwayRequest),
        /// / Informs the scheduler about the result of an execution request.
        #[prost(message, tag = "4")]
        ExecuteResult(super::ExecuteResult),
        /// / Notify that the execution has completed, but result is uploading.
        #[prost(message, tag = "5")]
        ExecuteComplete(super::ExecuteComplete),
    }
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct StartExecute {
    /// / The action information used to execute job.
    #[prost(message, optional, tag = "1")]
    pub execute_request: ::core::option::Option<
        super::super::super::super::super::build::bazel::remote::execution::v2::ExecuteRequest,
    >,
    /// / Id of the operation.
    #[prost(string, tag = "4")]
    pub operation_id: ::prost::alloc::string::String,
    /// / The time at which the command was added to the queue to allow population
    /// / of the ActionResult.
    #[prost(message, optional, tag = "3")]
    pub queued_timestamp: ::core::option::Option<::prost_types::Timestamp>,
    /// / The post-computed platform properties that the scheduler has reserved for
    /// / the action.
    #[prost(message, optional, tag = "5")]
    pub platform: ::core::option::Option<
        super::super::super::super::super::build::bazel::remote::execution::v2::Platform,
    >,
    /// / The ID of the worker that is executing the action.
    #[prost(string, tag = "6")]
    pub worker_id: ::prost::alloc::string::String,
}
/// / This is a special message used to save actions into the CAS that can be used
/// / by programs like bb_browswer to inspect the history of a build.
/// / Note: Ensure this is always compatible with:
/// / <https://github.com/buildbarn/bb-remote-execution/blob/e95e066eb624dc9099682394ec18c12e218e8fc4/pkg/proto/cas/cas.proto#L23>
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HistoricalExecuteResponse {
    #[prost(message, optional, tag = "1")]
    pub action_digest: ::core::option::Option<
        super::super::super::super::super::build::bazel::remote::execution::v2::Digest,
    >,
    #[prost(message, optional, tag = "3")]
    pub execute_response: ::core::option::Option<
        super::super::super::super::super::build::bazel::remote::execution::v2::ExecuteResponse,
    >,
}
/// Generated client implementations.
pub mod worker_api_client {
    #![allow(
        unused_variables,
        dead_code,
        missing_docs,
        clippy::wildcard_imports,
        clippy::let_unit_value,
    )]
    use tonic::codegen::*;
    use tonic::codegen::http::Uri;
    /// / This API describes how schedulers communicate with Worker nodes.
    /// /
    /// / When a worker node comes online it must be pre-configured with the
    /// / endpoint of the scheduler it will register with. Once the worker
    /// / connects to the scheduler it must send a `ConnectWorkerRequest`
    /// / command to the scheduler. The scheduler will then use this information
    /// / to determine which jobs the worker can process.
    #[derive(Debug, Clone)]
    pub struct WorkerApiClient<T> {
        inner: tonic::client::Grpc<T>,
    }
    impl<T> WorkerApiClient<T>
    where
        T: tonic::client::GrpcService<tonic::body::Body>,
        T::Error: Into<StdError>,
        T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
        <T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
    {
        pub fn new(inner: T) -> Self {
            let inner = tonic::client::Grpc::new(inner);
            Self { inner }
        }
        pub fn with_origin(inner: T, origin: Uri) -> Self {
            let inner = tonic::client::Grpc::with_origin(inner, origin);
            Self { inner }
        }
        pub fn with_interceptor<F>(
            inner: T,
            interceptor: F,
        ) -> WorkerApiClient<InterceptedService<T, F>>
        where
            F: tonic::service::Interceptor,
            T::ResponseBody: Default,
            T: tonic::codegen::Service<
                http::Request<tonic::body::Body>,
                Response = http::Response<
                    <T as tonic::client::GrpcService<tonic::body::Body>>::ResponseBody,
                >,
            >,
            <T as tonic::codegen::Service<
                http::Request<tonic::body::Body>,
            >>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
        {
            WorkerApiClient::new(InterceptedService::new(inner, interceptor))
        }
        /// Compress requests with the given encoding.
        ///
        /// This requires the server to support it otherwise it might respond with an
        /// error.
        #[must_use]
        pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
            self.inner = self.inner.send_compressed(encoding);
            self
        }
        /// Enable decompressing responses.
        #[must_use]
        pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
            self.inner = self.inner.accept_compressed(encoding);
            self
        }
        /// Limits the maximum size of a decoded message.
        ///
        /// Default: `4MB`
        #[must_use]
        pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
            self.inner = self.inner.max_decoding_message_size(limit);
            self
        }
        /// Limits the maximum size of an encoded message.
        ///
        /// Default: `usize::MAX`
        #[must_use]
        pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
            self.inner = self.inner.max_encoding_message_size(limit);
            self
        }
        /// / Registers this worker and informs the scheduler what properties
        /// / this worker supports. The response must be listened on the client
        /// / side for updates from the server.  This is performed as a single
        /// / bi-directional call to ensure that the worker is always talking to the
        /// / same scheduler instance even if there's a load balancer in front.
        /// / The first message on the UpdateForScheduler stream will be a
        /// / ConnectWorkerRequest which will notify the scheduler of the available
        /// / properties and the first response will be a ConnectionResult to tell
        /// / the worker what worker ID to place in action results.
        pub async fn connect_worker(
            &mut self,
            request: impl tonic::IntoStreamingRequest<
                Message = super::UpdateForScheduler,
            >,
        ) -> std::result::Result<
            tonic::Response<tonic::codec::Streaming<super::UpdateForWorker>>,
            tonic::Status,
        > {
            self.inner
                .ready()
                .await
                .map_err(|e| {
                    tonic::Status::unknown(
                        format!("Service was not ready: {}", e.into()),
                    )
                })?;
            let codec = tonic::codec::ProstCodec::default();
            let path = http::uri::PathAndQuery::from_static(
                "/com.github.trace_machina.nativelink.remote_execution.WorkerApi/ConnectWorker",
            );
            let mut req = request.into_streaming_request();
            req.extensions_mut()
                .insert(
                    GrpcMethod::new(
                        "com.github.trace_machina.nativelink.remote_execution.WorkerApi",
                        "ConnectWorker",
                    ),
                );
            self.inner.streaming(req, path, codec).await
        }
    }
}
/// Generated server implementations.
pub mod worker_api_server {
    #![allow(
        unused_variables,
        dead_code,
        missing_docs,
        clippy::wildcard_imports,
        clippy::let_unit_value,
    )]
    use tonic::codegen::*;
    /// Generated trait containing gRPC methods that should be implemented for use with WorkerApiServer.
    #[async_trait]
    pub trait WorkerApi: std::marker::Send + std::marker::Sync + 'static {
        /// Server streaming response type for the ConnectWorker method.
        type ConnectWorkerStream: tonic::codegen::tokio_stream::Stream<
                Item = std::result::Result<super::UpdateForWorker, tonic::Status>,
            >
            + std::marker::Send
            + 'static;
        /// / Registers this worker and informs the scheduler what properties
        /// / this worker supports. The response must be listened on the client
        /// / side for updates from the server.  This is performed as a single
        /// / bi-directional call to ensure that the worker is always talking to the
        /// / same scheduler instance even if there's a load balancer in front.
        /// / The first message on the UpdateForScheduler stream will be a
        /// / ConnectWorkerRequest which will notify the scheduler of the available
        /// / properties and the first response will be a ConnectionResult to tell
        /// / the worker what worker ID to place in action results.
        async fn connect_worker(
            &self,
            request: tonic::Request<tonic::Streaming<super::UpdateForScheduler>>,
        ) -> std::result::Result<
            tonic::Response<Self::ConnectWorkerStream>,
            tonic::Status,
        >;
    }
    /// / This API describes how schedulers communicate with Worker nodes.
    /// /
    /// / When a worker node comes online it must be pre-configured with the
    /// / endpoint of the scheduler it will register with. Once the worker
    /// / connects to the scheduler it must send a `ConnectWorkerRequest`
    /// / command to the scheduler. The scheduler will then use this information
    /// / to determine which jobs the worker can process.
    #[derive(Debug)]
    pub struct WorkerApiServer<T> {
        inner: Arc<T>,
        accept_compression_encodings: EnabledCompressionEncodings,
        send_compression_encodings: EnabledCompressionEncodings,
        max_decoding_message_size: Option<usize>,
        max_encoding_message_size: Option<usize>,
    }
    impl<T> WorkerApiServer<T> {
        pub fn new(inner: T) -> Self {
            Self::from_arc(Arc::new(inner))
        }
        pub fn from_arc(inner: Arc<T>) -> Self {
            Self {
                inner,
                accept_compression_encodings: Default::default(),
                send_compression_encodings: Default::default(),
                max_decoding_message_size: None,
                max_encoding_message_size: None,
            }
        }
        pub fn with_interceptor<F>(
            inner: T,
            interceptor: F,
        ) -> InterceptedService<Self, F>
        where
            F: tonic::service::Interceptor,
        {
            InterceptedService::new(Self::new(inner), interceptor)
        }
        /// Enable decompressing requests with the given encoding.
        #[must_use]
        pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
            self.accept_compression_encodings.enable(encoding);
            self
        }
        /// Compress responses with the given encoding, if the client supports it.
        #[must_use]
        pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
            self.send_compression_encodings.enable(encoding);
            self
        }
        /// Limits the maximum size of a decoded message.
        ///
        /// Default: `4MB`
        #[must_use]
        pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
            self.max_decoding_message_size = Some(limit);
            self
        }
        /// Limits the maximum size of an encoded message.
        ///
        /// Default: `usize::MAX`
        #[must_use]
        pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
            self.max_encoding_message_size = Some(limit);
            self
        }
    }
    impl<T, B> tonic::codegen::Service<http::Request<B>> for WorkerApiServer<T>
    where
        T: WorkerApi,
        B: Body + std::marker::Send + 'static,
        B::Error: Into<StdError> + std::marker::Send + 'static,
    {
        type Response = http::Response<tonic::body::Body>;
        type Error = std::convert::Infallible;
        type Future = BoxFuture<Self::Response, Self::Error>;
        fn poll_ready(
            &mut self,
            _cx: &mut Context<'_>,
        ) -> Poll<std::result::Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }
        fn call(&mut self, req: http::Request<B>) -> Self::Future {
            match req.uri().path() {
                "/com.github.trace_machina.nativelink.remote_execution.WorkerApi/ConnectWorker" => {
                    #[allow(non_camel_case_types)]
                    struct ConnectWorkerSvc<T: WorkerApi>(pub Arc<T>);
                    impl<
                        T: WorkerApi,
                    > tonic::server::StreamingService<super::UpdateForScheduler>
                    for ConnectWorkerSvc<T> {
                        type Response = super::UpdateForWorker;
                        type ResponseStream = T::ConnectWorkerStream;
                        type Future = BoxFuture<
                            tonic::Response<Self::ResponseStream>,
                            tonic::Status,
                        >;
                        fn call(
                            &mut self,
                            request: tonic::Request<
                                tonic::Streaming<super::UpdateForScheduler>,
                            >,
                        ) -> Self::Future {
                            let inner = Arc::clone(&self.0);
                            let fut = async move {
                                <T as WorkerApi>::connect_worker(&inner, request).await
                            };
                            Box::pin(fut)
                        }
                    }
                    let accept_compression_encodings = self.accept_compression_encodings;
                    let send_compression_encodings = self.send_compression_encodings;
                    let max_decoding_message_size = self.max_decoding_message_size;
                    let max_encoding_message_size = self.max_encoding_message_size;
                    let inner = self.inner.clone();
                    let fut = async move {
                        let method = ConnectWorkerSvc(inner);
                        let codec = tonic::codec::ProstCodec::default();
                        let mut grpc = tonic::server::Grpc::new(codec)
                            .apply_compression_config(
                                accept_compression_encodings,
                                send_compression_encodings,
                            )
                            .apply_max_message_size_config(
                                max_decoding_message_size,
                                max_encoding_message_size,
                            );
                        let res = grpc.streaming(method, req).await;
                        Ok(res)
                    };
                    Box::pin(fut)
                }
                _ => {
                    Box::pin(async move {
                        let mut response = http::Response::new(
                            tonic::body::Body::default(),
                        );
                        let headers = response.headers_mut();
                        headers
                            .insert(
                                tonic::Status::GRPC_STATUS,
                                (tonic::Code::Unimplemented as i32).into(),
                            );
                        headers
                            .insert(
                                http::header::CONTENT_TYPE,
                                tonic::metadata::GRPC_CONTENT_TYPE,
                            );
                        Ok(response)
                    })
                }
            }
        }
    }
    impl<T> Clone for WorkerApiServer<T> {
        fn clone(&self) -> Self {
            let inner = self.inner.clone();
            Self {
                inner,
                accept_compression_encodings: self.accept_compression_encodings,
                send_compression_encodings: self.send_compression_encodings,
                max_decoding_message_size: self.max_decoding_message_size,
                max_encoding_message_size: self.max_encoding_message_size,
            }
        }
    }
    /// Generated gRPC service name
    pub const SERVICE_NAME: &str = "com.github.trace_machina.nativelink.remote_execution.WorkerApi";
    impl<T> tonic::server::NamedService for WorkerApiServer<T> {
        const NAME: &'static str = SERVICE_NAME;
    }
}
